#include <iostream>
#include <string>
#include <cstdio>
#include <string.h>
#include <errno.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    pid_t id = fork();
    if(id < 0 )
    {
        printf("errno: %d, errstring: %s\n",errno, strerror(errno));
        return errno;
    }
    else if(id == 0)
    {
        int cnt = 5;
        while(true)
        {
            printf("子进程运行中, pid: %d\n", getpid());
            cnt--;
            sleep(1);
        }
        //int *p = nullptr;
        //*p = 100;
        exit(123);
    }
    else 
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0); 
        if(rid > 0)
        {
            printf("wait sub process success, rid: %d, status code: %d, exit signal: %d\n", rid, (status>>8)&0xFF, status&0x7F);
            // 退出信息右移8位，得到退出信息所在的退出码bite再 &255，就得到退出码
        }
        else 
        {
            perror("waitpid");
        }
        while(true)
        {
            printf("我是父进程：pid: %d\n",getpid());
            sleep(1);
        }
    }

//    while(true)
//    {
//        int a = 1/0;
//        printf("hello world, pid: %d\n", getpid());
//        sleep(1);
//    }

   // char *p = nullptr;
   // *p = 'a';
    
    return 0;
}
